#coding=utf-8
#!/usr/bin/python

'''
Created on 2012-11-17

@author: Neo.Chen
'''

import os
import sys
sys.path.append("../")
import time
import string
import threading
from ktlib import ktlib
from ktlib import proc_monitor
from ktlib import sky
from ktlib import dataconvert

#默认命令行参数
g_process_name = "vcs_test"     #进程名字
g_bash_name = "./run_test.sh"   #启动脚本名字，放自己同一个目录
g_mgcount = 4                   #mg个数
g_mgindex = 0                   #当前mg索引

def app_restart(content):
    #重启进程
    os.system(g_bash_name)
    #发邮件通知
    ktlib.send_email("admin@sky-mobi.com", "neo.chen@sky-mobi.com", g_process_name + " restart", content)
    ktlib.send_email("admin@sky-mobi.com", "18758166494@139.com", g_process_name + " restart", content)
    ktlib.send_email("admin@sky-mobi.com", "tristan.yang@sky-mobi.com", g_process_name + " restart", content)
    ktlib.send_email("admin@sky-mobi.com", "13958110295@139.com", g_process_name + " restart", content)
    print("restart**********,content:", content , "\r\n")

#获取当前mg负责的房间id
def getMgRoomList(mgcount, mgindex):
    myIds = []
    roomids = []
    roomids = sky.getActiveRoom("www.52le.com", 80)
    for item in roomids:
        if (item % mgcount) == mgindex:
            myIds.append(item)
    return myIds



def main():
    print("main start...")
    proc = proc_monitor.CProcCpuMonitor(g_process_name, 800, 10, 3)
    while True:
        (isError, fCpu)= proc.checkIsError()
        if isError == True:
            app_restart("cpu is:%.1f, time:%s, roomlist:%s, mgindex:%d" % (fCpu, time.asctime(), getMgRoomList(g_mgcount, g_mgindex), g_mgindex))
        else:
            #每天定时重启一次
            #if proc_monitor.checkRestartForTime() == True:
            #    app_restart()
            pass
        time.sleep(60)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        g_process_name = sys.argv[1]
        g_bash_name = sys.argv[2]
        g_mgcount = dataconvert.str2int(sys.argv[3])
        g_mgindex = dataconvert.str2int(sys.argv[4])
        print(g_process_name)
        print(g_bash_name)
        print(g_mgcount)
        print(g_mgindex)
    else:
        print("cmd line param: vcs_test ./run_test.sh 4 1")
    ktlib.close_print()
    try:
        main()
    except:
        ktlib.write_crash_log()
